package com.ld.poetry.controller;

import com.ld.poetry.RedisService;
import com.ld.poetry.aop.LoginCheck;
import com.ld.poetry.config.PoetryResult;
import com.ld.poetry.entity.User;
import com.ld.poetry.im.http.entity.ImChatUserFriend;
import com.ld.poetry.im.http.service.ImChatUserFriendService;
import com.ld.poetry.im.websocket.ImConfigConst;
import com.ld.poetry.utils.CommonQuery;
import com.ld.poetry.utils.PoetryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/vortex")
public class VortexController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ImChatUserFriendService userFriendService;

    @Autowired
    private CommonQuery commonQuery;

    @GetMapping("/enterVortex")
    @LoginCheck
    public PoetryResult enterVortex() {
        Integer userId = PoetryUtil.getUserId();

        // 检查用户是否已经有好友
        if (hasFriend(userId)) {
            return PoetryResult.fail("您已经有好友，不能进入漩涡！");
        }

        // 检查漩涡中是否有等待的用户
        String waitingUserIdStr = redisService.get("vortex_waiting_user");
        if (waitingUserIdStr != null) {
            Integer waitingUserId = Integer.parseInt(waitingUserIdStr);
            // 检查两个用户是否已经是好友
            if (isFriend(userId, waitingUserId)) {
                return PoetryResult.fail("您与等待的用户已经是好友！");
            }
            // 如果有等待的用户，将两个用户添加为好友
            addFriend(userId, waitingUserId);
            // 删除等待的用户 ID
            redisService.delete("vortex_waiting_user");
            return PoetryResult.success("已与等待的用户成为好友！");
        } else {
            // 如果没有等待的用户，将当前用户 ID 存入 Redis
            redisService.set("vortex_waiting_user", userId.toString());
            return PoetryResult.success("已进入漩涡，等待其他用户！");
        }
    }

    private boolean hasFriend(Integer userId) {
        // 检查用户是否已经有好友
        Integer count = userFriendService.lambdaQuery()
                .and(wrapper -> wrapper.eq(ImChatUserFriend::getUserId, userId)
                        .or().eq(ImChatUserFriend::getFriendId, userId))
                .count();
        return count > 0;
    }

    private boolean isFriend(Integer userId, Integer friendId) {
        // 检查两个用户是否已经是好友
        Integer count = userFriendService.lambdaQuery()
                .and(wrapper -> wrapper.eq(ImChatUserFriend::getUserId, userId).eq(ImChatUserFriend::getFriendId, friendId)
                        .or().eq(ImChatUserFriend::getUserId, friendId).eq(ImChatUserFriend::getFriendId, userId))
                .count();
        return count > 0;
    }

    private void addFriend(Integer userId, Integer friendId) {
        if (userId.equals(friendId)) {
            throw new IllegalArgumentException("不能添加自己为好友！");
        }
        // 添加好友逻辑
        ImChatUserFriend imChatFriend1 = new ImChatUserFriend();
        imChatFriend1.setUserId(userId);
        imChatFriend1.setFriendId(friendId);
        imChatFriend1.setFriendStatus(ImConfigConst.FRIEND_STATUS_PASS);
        userFriendService.save(imChatFriend1);

        ImChatUserFriend imChatFriend2 = new ImChatUserFriend();
        imChatFriend2.setUserId(friendId);
        imChatFriend2.setFriendId(userId);
        imChatFriend2.setFriendStatus(ImConfigConst.FRIEND_STATUS_PASS);
        userFriendService.save(imChatFriend2);
    }

    /**
     * 查询当前用户信息
     */
    @GetMapping("/getCurrentUser")
    @LoginCheck
    public PoetryResult<User> getCurrentUser() {
        Integer userId = PoetryUtil.getUserId();
        User currentUser = commonQuery.getUser(userId);
        return PoetryResult.success(currentUser);
    }
}
